package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
	"time"
)

func main() {
	// docker-compose 用
	conn, err := net.DialTimeout("tcp", ":8011", time.Second*2)

	// k8s 用
	// conn, err := net.DialTimeout("tcp", "192.168.34.4:30011", time.Second*2)
	if err != nil {
		fmt.Println("dial err: ", err)
		return
	}

	// 先读第一条消息，来自代理的连接提示
	receiver := bufio.NewReader(conn)
	msg, err := receiver.ReadString('\n')
	if err != nil || strings.TrimSpace(msg) != "ok" {
		fmt.Println("read first msg error: ", err)
		return
	}
	fmt.Println("connect success, pls input:")

	// 正常消息收发，消息以回车符结尾
	input := bufio.NewReader(os.Stdin)
	for {
		in, err := input.ReadString('\n')
		if err != nil {
			fmt.Println("read from console failed: ", err)
			break
		}
		in = strings.TrimSpace(in)
		if in == "" {
			continue
		}

		_, err = conn.Write([]byte(in))
		if err != nil {
			fmt.Println("write failed: ", err)
			break
		}
		if in == "quit" {
			break
		}

		msg, err := receiver.ReadString('\n')
		if err != nil {
			fmt.Println("read msg error: ", err)
			return
		}
		fmt.Println("recv: ", msg)
	}
}
